package com.yq.controller;

import com.google.gson.Gson;
import com.sun.corba.se.spi.orbutil.fsm.FSM;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import com.yq.model.Result;
import com.yq.model.bo.AddAdminBO;
import com.yq.model.bo.AdminInfoBO;
import com.yq.model.bo.AdminLoginBO;
import com.yq.model.po.Admin;
import com.yq.model.vo.AdminInfoVO;
import com.yq.model.vo.AdminLoginVO;
import com.yq.service.AdminService;
import com.yq.service.impl.AdminServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.ReuseExecutor;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@WebServlet("/api/admin/admin/*")
public class AdminServlet extends HttpServlet {
     private AdminService adminService = new AdminServiceImpl();
     private Gson gson = new Gson();


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replace(request.getContextPath() + "/api/admin/admin/", "");
        if ("login".equals(op)){
            login(request,response);
        }else if ("addAdminss".equals(op)){
            addAdminss(request,response);
        }else if ("updateAdminss".equals(op)){
            updateAdminss(request,response);
        }else if ("getSearchAdmins".equals(op)){
            getSearchAdmins(request,response);
        }
    }


    /**
     * 根据email和nickname查找用户信息
     * @param request
     * @param response
     */
    private void getSearchAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 1 获取请求参数
        String requestInfo = getRequestInfo(request);
        // TODO: 2022.8.19 {nickname: "admin", email: "admin"}
        // 2 转换为java对象 bo
        AdminInfoBO adminInfoBO = gson.fromJson(requestInfo, AdminInfoBO.class);

        // 3 查询
        // 需要返回的结果 {"code":0,"data":[{"id":1,"email":"admin","nickname":"admin","pwd":"admin"}]}
        List<AdminInfoVO> list = adminService.getSearchAdmins(adminInfoBO);
        response.getWriter().println(gson.toJson(new Result(0,null,list)));

    }

    /**
     * 修改用户的信息
     * @param request
     * @param response
     */

    private void updateAdminss(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求参数
        String requestInfo = getRequestInfo(request);
        // TODO {"id": 10,"nickname": "op12345","email": "33072355@qq.com","pwd": "Op12345678#"}
        AdminInfoBO adminInfoBO = gson.fromJson(requestInfo, AdminInfoBO.class);
        int code  = adminService.updateAdminInfo(adminInfoBO);
        Result result=null;
        if (code==200){
            result = new Result(0,null,null);
        }else if (code==404){
            // TODo {"code":10000,"message":"该账号不允许重复使用"}
            result =new Result(10000,"该账号不允许重复使用",null);
        }
        response.getWriter().println(gson.toJson(result));

    }

    /** addAdminss 添加管理员用户
     * 请求的url /api/admin/admin/addAdminss
     * @param request
     * @param response
     */

    private void addAdminss(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //Todo 1 数据格式{nickname: "yqlcy", email: "3307235355@qq.com", pwd: "Yq3307235355#"}
        String requestInfo = getRequestInfo(request);
        // 2 数据一定是合法的 插入
        AddAdminBO addAdminBO = gson.fromJson(requestInfo, AddAdminBO.class);
        int code  = adminService.addAdmin(addAdminBO);

        // TODO: 2022.8.19  创建完成的 {"code":0} 失败的{"code":10000,"message":"该账号不允许重复使用"}
        Result result=null;
        if (code==200){
            result=new Result(0,null,null);
        }else if(code==404){
            result=new Result(10000,"该账号不允许重复使用",null);
        }
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 获取请求的参数
     *
     * @param request
     * @return
     * @throws IOException
     */

    private String getRequestInfo(HttpServletRequest request) throws IOException {
        //获取数据
        ServletInputStream inputStream = request.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int leng;
        while ((leng = inputStream.read(bytes))!=-1){
            byteArrayOutputStream.write(bytes,0,leng);
        }
        String requestInfo = byteArrayOutputStream.toString();
        byteArrayOutputStream.close();
        return requestInfo;
    }

    /**
     * 登录验证 请求的url /api/admin/admin/login
     * @param request
     * @param response
     * @throws IOException
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 1 数据的获取
        String requestInfo = getRequestInfo(request);
        //登录处理 首先在这里直接的判断是否合法，再去验证数据库的密码
        AdminLoginBO adminLoginBO = gson.fromJson(requestInfo, AdminLoginBO.class);
        if (StringUtils.isEmpty(adminLoginBO.getEmail())|| StringUtils.isEmpty(adminLoginBO.getPwd())){
            // TODO 返回参数的格式  {"code":10000,"message":"该账号不存在"}
            Result result = new Result(0,"输入信息不正确",null);
            response.getWriter().println(gson.toJson(result));
            return;
        }
        //下一步数据库的验证
      int code = adminService.login(adminLoginBO);
        Result result=null;

        if (code ==200){
            //TODO 登录成功返回{"code":0,"data":{"token":"admin","name":"admin"}}
            //创建返回的vo类
            AdminLoginVO adminLoginVO = new AdminLoginVO();
            adminLoginVO.setToken(adminLoginBO.getEmail());
            adminLoginVO.setName(adminLoginBO.getEmail());
            result = new Result(0,null,adminLoginVO);
        }else if (code ==404){
            result = new Result(0,"输入信息不正确",null);
        }
        response.getWriter().println(gson.toJson(result));



    }





    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replace(request.getContextPath() + "/api/admin/admin/", "");
        if ("allAdmins".equals(op)){
            allAdmins(request,response);
        }else if ("getAdminsInfo".equals(op)){
            getAdminsInfo(request,response);
        }else if ("deleteAdmins".equals(op)){
            deleteAdmins(request,response);
        }

    }

    /**
     * 删除用户  /api/admin/deleteAdmins?id=19
     * 参数是用户的id
     * @param request
     * @param response
     */

    private void deleteAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 1 获取用户的id
        String id = request.getParameter("id");

        // 2 根据id删除
       int code  =  adminService.deleteAdminById(Integer.parseInt(id));
       Result result=null;
       if (code==200){
           result=new Result(0,null,null);
       }
        response.getWriter().println(gson.toJson(result));

    }

    /**
     * 点击修改用户，不是真正的修改而是获取用户的信息
     * 请求的url /api/admin/getAdminsInfo?id=10
     * @param request
     * @param response
     */

    private void getAdminsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1 获取用户的id
        String id = request.getParameter("id");
        // 2 根据id去查询值
        //// TODO: 2022.8.19 {"code":0,"data":{"id":10,"email":"3307235@qq.com","nickname":"op12345","pwd":"Op12345678#"}}
        AdminInfoVO adminInfoVO  = adminService.queryById(Integer.parseInt(id));
        response.getWriter().println(gson.toJson(new Result(0,null,adminInfoVO)));

    }


    /**
     * 查询所有的用户超级用户的信息
     * 请求的url /api/admin/admin/allAdmins
     * @param request
     * @param response
     * @throws IOException
     */
    private void allAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //TODO {"code":0,"data":[{"id":1,"email":"admin","nickname":"admin","pwd":"admin"}]}
        // 查询所有的数据
        List<AdminInfoVO> adminInfoVOList =  adminService.queryAllAdmin();
        response.getWriter().println(gson.toJson(new Result(0,null,adminInfoVOList)));


    }



}
